﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;

namespace Appology.SugarSync.Explorer.Phone
{
    public partial class Settings : PhoneApplicationPage
    {
        public Settings()
        {
            InitializeComponent();

            var username = ApplicationState.Current.Username;
            var password = ApplicationState.Current.Password;

            Username.Text = username ?? string.Empty;
            Password.Password = password ?? string.Empty;
        }

        private async void Save_Click(object sender, System.EventArgs e)
        {
            if(string.IsNullOrEmpty(Username.Text))
            {
                MessageBox.Show("Username is required.");
            }

            if(string.IsNullOrEmpty(Password.Password))
            {
                MessageBox.Show("Password is required.");
            }

            ApplicationState.Current.Username = Username.Text;
            ApplicationState.Current.Password = Password.Password;

            ApplicationState.Current.Save();

            var applicationState = ApplicationState.Current;

            applicationState.Account.SetUserCredentials(Username.Text, Password.Password);

            if (await applicationState.Account.AuthenticateAsync())
            {
                await applicationState.Account.RefreshAsync();

                await applicationState.StorageRoot.RefreshAsync();

                if (applicationState.History.Count == 0)
                {
                    applicationState.History.Push(applicationState.StorageRoot);
                }

                NavigationService.Navigate(new Uri("/Browse.xaml", UriKind.Relative));
            }
            else
            {
                MessageBox.Show("Invalid account information.  Please try again.");
            }
        }
    }
}